﻿using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class UITipABUpdateProgressComponent : MonoBehaviour
{
    public BundleDownloadInfo DownLoadInfo;
    //public Text textSpeed;
    //public Text textPercent;
    //public Image imageSlider;
    public Image imageAnimRotate;
    public Text textPercent;

    const float cyclePerSecond = 0.2f;
    float cyclePerFrame;
    float countCycle=0f;
    private float lastTime = 0;
    /// <summary>
    /// 20帧刷新一次
    /// </summary>
    private int updateFrameEvery = 1;
    private int frame = 0;
    private long lastDownloaded;

    // Start is called before the first frame update
    void Start()
    {
        imageAnimRotate.fillAmount = 1f;
        countCycle = 0f;
        cyclePerFrame = cyclePerSecond / 50f;
    }
    public void UpdateShow()
    {
        //textSpeed.text = DownLoadInfo.SpeedString;
        textPercent.text = $"{DownLoadInfo.Progress}%";
        //imageSlider.fillAmount = DownLoadInfo.Progress / 100f;
    }
    // Update is called once per frame
    void Update()
    {
        if (DownLoadInfo.IsEnd) return;
        if (DownLoadInfo == null) return;
        if (!DownLoadInfo.IsStart) return;

        //转圈
        countCycle += cyclePerFrame;
        var deltaCycle = 1 - countCycle;
        if (deltaCycle<=0)
        {
            countCycle = 0f;
            imageAnimRotate.fillAmount = 1f;
        }
        imageAnimRotate.fillAmount = deltaCycle;

        var now = Time.realtimeSinceStartup;
        if (lastTime == 0)
        {
            lastDownloaded = DownLoadInfo.alreadyDownloadBytes;
            lastTime = now;
            return;
        }
        frame++;
        if (frame < updateFrameEvery) return;
        frame = 0;
        Debug.Log($"更新进度：{DownLoadInfo.Progress}");
        var passedTime = now - lastTime;
        var stepDownload = DownLoadInfo.alreadyDownloadBytes - lastDownloaded;

        lastDownloaded = DownLoadInfo.alreadyDownloadBytes;
        lastTime = now;

        var t = stepDownload / passedTime;
        DownLoadInfo.DownLoadSpeed = t;
        UpdateShow();
    }
}
